using B.S.Data.MES.API.Applications.CangKu.Command;
using B.S.Domain;
using B.S.Domain.CangKu;
using B.S.Domain.Warehousemanagement.Inventoryinquiry.FinishedProductWarehouseModels;
using B.S.Infratrctrue;
using B.S.Requst;
using MediatR;
using Microsoft.AspNetCore.SignalR;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.Data.MES.API.Applications.CangKu.CommandHandlers
{
    /// <summary>
    /// 添加Tel表数据命令处理器
    /// </summary>
    public class AddTelCommandHandler : IRequestHandler<AddTelCommand, APIRequst<int>>
    {
        private readonly IBaseRepository<CangKuinfo> _cangKuRepository;
        private readonly IBaseRepository<CangKuQU> _cangKuQURepository;
        private readonly IBaseRepository<ChuWei> _chuWeiRepository;
        private readonly IBaseRepository<RuKuinfo> _ruKuRepository;
        private readonly IBaseRepository<Tel> _telRepository;
        private readonly IBaseRepository<FinishedProductWarehouses> _finishedProductRepository;
        private readonly IHubContext<Hubtel> _hubContext;

        /// <summary>
        /// 构造函数，注入所需仓储和SignalR Hub上下文
        /// </summary>
        public AddTelCommandHandler(
            IBaseRepository<CangKuinfo> cangKuRepository,
            IBaseRepository<CangKuQU> cangKuQURepository,
            IBaseRepository<ChuWei> chuWeiRepository,
            IBaseRepository<RuKuinfo> ruKuRepository,
            IBaseRepository<Tel> telRepository,
            IBaseRepository<FinishedProductWarehouses> finishedProductRepository,
            IHubContext<Hubtel> hubContext)
        {
            _cangKuRepository = cangKuRepository;
            _cangKuQURepository = cangKuQURepository;
            _chuWeiRepository = chuWeiRepository;
            _ruKuRepository = ruKuRepository;
            _telRepository = telRepository;
            _finishedProductRepository = finishedProductRepository;
            _hubContext = hubContext;
        }

        /// <summary>
        /// 处理添加Tel表数据命令
        /// </summary>
        public async Task<APIRequst<int>> Handle(AddTelCommand request, CancellationToken cancellationToken)
        {
            // 为了保证事务内一致性，使用仓储的DbContext来查询并更新
            var db = _telRepository.db;

            using var transaction = await db.Database.BeginTransactionAsync(cancellationToken);
            try
            {
                // 计算仓库数量
                int cangKuCount = await db.Set<CangKuinfo>().CountAsync(cancellationToken);
                
                // 计算库位数量
                int kuQuCount = await db.Set<CangKuQU>().CountAsync(cancellationToken);
                
                // 计算储位数量
                int chuWeiCount = await db.Set<ChuWei>().CountAsync(cancellationToken);
                
                // 计算产品总数量
                int canNum = await db.Set<RuKuinfo>().SumAsync(r => r.ProductCount, cancellationToken);
                
                // 根据请求中的CanType获取产品名称
                string productName = "默认类型";
                
                if (!string.IsNullOrEmpty(request.CanType))
                {
                    // 尝试从成品表中获取产品名称
                    var product = await db.Set<FinishedProductWarehouses>()
                        .FirstOrDefaultAsync(p => p.ProductName == request.CanType, cancellationToken);
                    
                    if (product != null)
                    {
                        // 如果找到匹配的产品名称，使用该名称
                        productName = product.ProductName;
                    }
                    else
                    {
                        // 如果找不到匹配的产品名称，使用请求中的CanType值
                        productName = request.CanType;
                    }
                }
                
                // 创建Tel记录
                var tel = new Tel
                {
                    CangKuCount = cangKuCount,
                    KuQuCount = kuQuCount,
                    ChuWeiCount = chuWeiCount,
                    CanNum = canNum,
                    CanType = productName,
                    Time = DateTime.Now
                };
                
                // 添加到数据库
                db.Set<Tel>().Add(tel);
                await db.SaveChangesAsync(cancellationToken);
                
                // 提交事务
                await transaction.CommitAsync(cancellationToken);
                
                // 获取最新的Tel数据列表用于实时通信
                var latestTelData = await db.Set<Tel>()
                    .OrderByDescending(t => t.Time)
                    .Take(10) // 获取最新的10条记录
                    .ToListAsync(cancellationToken);
                
                // 通过SignalR发送最新数据到所有客户端
                await _hubContext.Clients.All.SendAsync("ReceiveTelData", latestTelData, cancellationToken);
                
                return new APIRequst<int>
                {
                    Code = RequstCode.成功,
                    Msg = "Tel表数据添加成功",
                    Data = tel.TelId
                };
            }
            catch (Exception ex)
            {
                try
                {
                    await transaction.RollbackAsync(cancellationToken);
                }
                catch { /* 忽略回滚错误 */ }
                
                return new APIRequst<int>
                {
                    Code = RequstCode.失败,
                    Msg = $"添加Tel表数据失败：{ex.Message}"
                };
            }
        }
    }
}